if (typeof uft == 'undefined') uft = {};
uft.profilesData =[]
uft.serverData= [];
uft.taskObjects={}
uft.selectedTaskList=[];
uft.timers={};
uft.taskStatus={1: "Running", 2:"Completed", 3:"Error", 4:"Stopped", 5:"Scheduled"}

uft.updateMainContainer = function(page){
	$("#mainContainer").atf_display_loader("Loading...")
	$("#mainContainer").load(page);
};

uft.updateHrefDiv=  function(divId, page){
	$("#divId").atf_display_loader("Loading...")
	$("#"+divId).load(page);
}

uft.init = function() {
	dwr.engine.setActiveReverseAjax(true);
	dwr.engine.setErrorHandler(uft.errorHandler);
	//console.log("onLoad");
	/* clearing and initializing the Notification Panel */
	uft.setNotificationCount(0);
	notificationUpdater.enableNotification();
	uft.loadServerData();
	uft.updateSchedulerBadge();
	if( !jQuery.isEmptyObject(uft.serverData)){
		var serverIds=[];
		jQuery.each( uft.serverData, function( i, val ) {
			serverIds.push(val.id)
		})
		serverTaskStatusUpdater.addServersIdToScriptSession(serverIds);
	}
	
	serverTaskStatusUpdater.updateAllTasks();
	
	
};



uft.errorHandler=function(message,ex){
	$('index-alert-container').atf_alert_flyover("Cannot connect to server. Initializing retry logic.", "Oh Snap!")
	//dwr.util.setValue("	", "Cannot connect to server. Initializing retry logic.", {escapeHtml:false});
	//setTimeout(function() { dwr.util.setValue("connectErrorDeploy", ""); }, 5000)

}



uft.setNotificationCount=function(count){
	var cCount=$("#notificationIconCount").text()
	$("#notificationIconCount").text(parseInt(cCount)+count);
}

uft.setTasksIconCount= function(count){
	var count = 0
	$.each(uft.taskObjects, function(index, value) {
	    count++;
	})
	$("#tasksIconCount").text(count);
	$("#currentTasksList h1").text(count)
}
uft.addNotificationEntry = function(taskObject){
	var date = new Date();
	var n = date.toDateString();
	var time = date.toLocaleTimeString();

	var notificationEntry=$('<li>', {
        html: $('<a>', {
             href: "#",
             html : $('<div>', {
            	 html: [ $('<i>', {
            		 'class': "fa fa-bell fa-fw"      		
            	 	}),
            	 	taskObject.serverName+" "+taskObject.comment,
            	 	$('<span>', {
            	 		'class': "pull-right text-muted small",
            	 		'text':  time
            	 	})
            	 ]
             })

        })

    });
	var divider=$('<li>', {
		 'class': "divider",
	})
	var divDivider=$('<div>', {
		 'class':  "divider",
	})
	var notificationPanelEntry =$("<div>",{
		'class': "row",
		
		style: 'margin-bottom: 5px;',
		html:[ $('<div>',{
			'class': "col-md-8",
			
			html: [$('<i>', {
	            		 'class': "fa fa-bell-o fa-fw"   
	            		
            	 	}),
            	 	taskObject.serverName+" "+taskObject.comment,
            	 ]
		}),
		
		$('<div>',{
			'class': "col-md-4",
			style: "color:red; text-decoration: blink;",
			text: time
		}),
		]
	})
	
	$("#notificationItemEntry li").first().after([divider, notificationEntry])
	if($("#notificationPanelContainer").length){
		$("#notificationPanelContainer").prepend([notificationPanelEntry,divDivider]);
	}
	uft.setNotificationCount(1)
	$("#index-alert-container").atf_info_flyover(taskObject.serverName+" "+taskObject.comment, taskObject.task)
	
}

uft.addOrUpdateDeployPanel = function(Obj){
	if(!jQuery.isEmptyObject(obj)){
		$("#deployDetails-serverName").text(Obj.serverName);
		$("#deployDetails-status").text(Obj.status);
	}
}

uft.updateServerTaskStatus= function(data){
	if(!jQuery.isEmptyObject(data)){
		//console.log(data)
		uft.taskObjects[data.taskId]=data
	}
	uft.loadServerTasks();	
}
uft.loadServerTasks = function(){
	if(!jQuery.isEmptyObject(uft.taskObjects)){
		jQuery.each( uft.taskObjects, function( key, val ) {
			val.task=val.task.toUpperCase();
			uft.addOrUpdateTaskStatusPanel(val.taskId,  val.status.toUpperCase(),val.task, val.serverName, val.comment);
		})
	}
}

uft.emailTaskDetails = function(subject, message){
	
		 profileController.sendAdminEmail(subject,message,{
				callback:function(data){
					uft.generateAlert(data, "#taskStatus-alert-container")
				}
		})
	
}

uft.updateTaskDetails = function(){
		if(!jQuery.isEmptyObject(uft.selectedTaskList)){
		 var taskId=uft.selectedTaskList[0];
		 if(!jQuery.isEmptyObject(uft.taskObjects)){
			var taskobj=uft.taskObjects[taskId];
			
			if(!jQuery.isEmptyObject(taskobj)){
				dwr.util.setValues([taskobj],{ idPrefix : 'taskStatus' })
			}
			if( $('#task_details').length > 0  && taskobj.status.toUpperCase()  != "COMPLETED"){
				setTimeout(function(){ 
					uft.updateTaskDetails(taskId);
				}, 5000);
			}else{
				uft.selectedTaskList = [];
			}
		
		 }else{
			 uft.selectedTaskList = [];
		 }
		}	
	}
uft.addOrUpdateTaskStatusPanel =function(taskId, taskStatus, task, serverName, description){
	var taskClassName="taskunknown";
	var trClassName;

	if(taskStatus == uft.taskStatus[1].toUpperCase()){
		taskClassName="taskrunning";
		trClassName= "info";
	}else if (taskStatus == uft.taskStatus[2].toUpperCase()){
		taskClassName="taskcompleted";
		trClassName= "success";
	}else if (taskStatus == uft.taskStatus[3].toUpperCase()){
		taskClassName="taskwarning";
		trClassName= "warning";
	}else if (taskStatus == uft.taskStatus[4].toUpperCase()){
		taskClassName="taskstopped";
		trClassName= "danger";
		
	}else if (taskStatus == uft.taskStatus[5].toUpperCase()){
		taskClassName="taskscheduled";
		trClassName= "info";
	}
	if($("#processStatus"+taskId).length){
		$("#processStatus"+taskId).attr( "class", trClassName )
		$("#processStatus"+taskId+" td:nth-child(1)").attr( "class", taskClassName )
		$("#processStatus"+taskId+" td:nth-child(2) a").text(taskStatus)
		$("#processStatus"+taskId+" td:nth-child(3)").text(task)
		$("#processStatus"+taskId+" td:nth-child(5)").text(description);
		
	}else{
		var process=$('<tr>', {
			 id:'processStatus'+taskId,
			 'class': trClassName,
			 html: [	
			        
						$('<td>', {
							'class': taskClassName,
							style: 'vertical-align: top;'
						}),
						$('<td>', {
							 html: [ $('<a>',{
								 
								 text:  taskStatus,
							 }).click( function(){
								 //uft.displayTaskOutput(taskId);
								 $("#task-output").load("jsp/taskDetails.jsp?taskId="+taskId);
							 })],
							 style: 'vertical-align: top;'
						}),
						$('<td>', {
							 text: task.toUpperCase(),
							 style: 'vertical-align: top;'
						}),
						$('<td>', {
							 text: serverName,
							 style: 'vertical-align: top;'
						}),
						$('<td>', {
							 text: description,
							 style: 'vertical-align: top;'
						}),
			       ]
		})
		$("#taskStatusContainer > tbody:first").prepend(process)
		uft.setTasksIconCount();
		
	}
	
}

uft.getProfileByType= function(type){
	var profiles;
	profileController.getProfilesByType(type,{
		 async: false,
		callback:function(data){
			profiles=data
		}
	});
	return profiles;
}

uft.getProfileByTypeRegion= function(type, region){
	var profiles;
	profileController.getProfileByTypeRegion(type,region,{
		 async: false,
		callback:function(data){
			profiles=data
		}
	});
	return profiles;
}
uft.getProfileUniqueRegions= function(){
	var profiles;
	profileController.getProfileUniqueRegions({
		 async: false,
		callback:function(data){
			profiles=data
		}
	});
	return profiles;
}

uft.getProfileRuntime= function() {
	var profileRuntime;
	taskManager.getProfileRuntimeDetails({
		async: false,
		callback:function(data){
			profileRuntime = data;
		}
 	}); 
	
	return profileRuntime;
}

uft.stopRuntimeProfile= function(profileId, responsediv){
	taskManager.stopProfileRuntimeDetails(profileId,{
		callback: function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Stopping the Runtime Profile");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
 	}); 
}


uft.loadProfilesData = function(){
	serverTaskStatusUpdater.removeProfileIdToScriptSession();
	if( jQuery.isEmptyObject(uft.profilesData)){
		profileController.getProfilesList({
			 async: false,
			callback:function(data){
				uft.profilesData=data
				
			}
		});
	}
	if(!jQuery.isEmptyObject(uft.profilesData)){
		var profileIds=[];
		jQuery.each( uft.profilesData, function( i, val ) {
			profileIds.push(val.id)
		})
		serverTaskStatusUpdater.addProfileIdToScriptSession(profileIds);
	}
};

uft.deleteProfile = function(id){
	if(id != ""){
		profileController.deleteProfile(id,{
			async: false,
			callback:function(data){
				$("#profile-alert-container").atf_success("Delete "+data)
			}
		});
	}
	uft.profilesData = []
	uft.loadProfilesData();
}
uft.saveOrUpdateProfile = function (profile){
	if(profile.id == ""){
		profileController.addProfile(profile,{
			async: false,
			callback:function(data){
				$("#profile-alert-container").atf_success("Add "+data)
				
			}
		});
	}else{
		profileController.updateProfile(profile,{
			async: false,
			callback:function(data){
				$("#profile-alert-container").atf_success("Update "+data)
				
			}
		});
	}
	uft.profilesData = []
	uft.loadProfilesData();
}
uft.getEmptyProfile = function(){
	var profile;
	profileController.getNewProfile({
		 async: false,
		callback:function(data){
			profile=data
			
		}
	});
	
	return profile;
} 

uft.getProfilePreferencesList = function(profileId){
	var profilePref;
	profileController.getProfilePreferencesList(profileId,{
		 async: false,
		callback:function(data){
			profilePref=data;
			
		}
	});
	return profilePref;
}
uft.getServerPreferencesList = function(serverId){
	var serverPref;
	serverController.getServerPreferencesList(serverId,{
		 async: false,
		callback:function(data){
			serverPref=data;
			
		}
	});
	return serverPref;
}

uft.getJobPreferencesList= function(jobId){
	var jobPref;
	schedulerController.getJobsPreferencesList(jobId,{
		 async: false,
		callback:function(data){
			jobPref=data;
			
		}
	});
	return jobPref;
}

uft.getPreferencesList = function(scope){
	var pref;
	preferenceController.getPreferencesListByScope(scope,{
		 async: false,
		callback:function(data){
			pref=data;	
		}
	});
	return pref;
}


uft.saveOrUpdatePreference= function(profileId, serverId,jobId,preference, responsediv){
	
	
    	if(preference.id == ""){
    		if(profileId != "null"){
    			
    			profileController.addPreference(profileId,preference, {
    				 async: false,
	       			callback:function(data){
	       				$("#"+responsediv).atf_success("Add "+data)
	       			}
       			})
    	    }else if (serverId != "null"){
    	    	serverController.addPreference(serverId,preference, {
    	    		 async: false,
	       			callback:function(data){
	       				$("#"+responsediv).atf_success("Add "+data)
	       			}
       			})
    	    }else if (jobId != "null"){
    	    	schedulerController.addPreference(jobId,preference, {
   	    		 async: false,
	       			callback:function(data){
	       				$("#"+responsediv).atf_success("Add "+data)
	       			}
      			})
    	    }else{
    	    	preferenceController.addPreference(preference,{
    	    	async: false,
       			callback:function(data){
       				$("#"+responsediv).atf_success("Add "+data)
       				
       			}
    	    	});
    	    }

    	}else{
    		preferenceController.updatePreference(preference,{
    			 async: false,
    			callback:function(data){
    				$("#"+responsediv).atf_success("Updated "+data)
    				
    			}
    		});
    	}
	
	
	
}

uft.deleteProfilePreference =function(profileId, prefId, responsediv ){
	profileController.deleteProfilePreference(profileId,prefId,{
		async: false,
		callback:function(data){
			$("#"+responsediv).atf_success("Delete: "+data)
		}
	});
}
uft.deleteServerPreference = function(serverId,prefId, responsediv){
	
	serverController.deleteServerPreference(serverId,prefId,{
		async: false,
		callback:function(data){
			$("#"+responsediv).atf_success("Delete: "+data)
		}
	});
}
uft.deleteJobPreference= function(jobId,prefId, responsediv){
	schedulerController.deletePreference(jobId,prefId,{
		async: false,
		callback:function(data){
			$("#"+responsediv).atf_success("Delete: "+data)
		}
	});
}
uft.deletePreference = function(profileId, serverId,jobId, prefId,responsediv){
	if(prefId != ""){
		if(profileId != "null"){
			uft.deleteProfilePreference(profileId,prefId,responsediv)
	    }else if (serverId != "null"){
	    	uft.deleteServerPreference(serverId,prefId,responsediv)
	    }else if (jobId != "null"){
	    	uft.deleteJobPreference(jobId,prefId,responsediv)
	    }else{
	    	preferenceController.deletePreference(prefId,{
	    		async: false,
				callback:function(data){
					$("#"+responsediv).atf_success("Delete: "+data)
					
				}
			});
	    }
		
	}
}
uft.loadServerData = function(){
	if( jQuery.isEmptyObject(uft.serverData)){
		serverController.getServerList({
			async: false,
			callback:function(data){
				uft.serverData=data
			}
		});
	}
	
}

uft.getServerFromLocal = function(serverId){
	if( !jQuery.isEmptyObject(uft.serverData)){
		jQuery.each( uft.serverData, function( i, val ) {
			if( val.id == serverId){
				return val;
			}
		})
	}
}

uft.getPreferenceList = function(profileId, serverId, jobId){
	    var prefList=[];
	    if(profileId != "null"){
	    	prefList= uft.getProfilePreferencesList(profileId);
	    }else if (serverId != "null"){
	    	prefList= uft.getServerPreferencesList(serverId);
	    }else if (jobId != "null"){
	    	prefList= uft.getJobPreferencesList(jobId);
	    }else{
	    	prefList=uft.getPreferencesList("GLOBAL");
	    }
	    return prefList;
}

uft.generateAlert = function(message, responsediv){
	var alertType="";
	if(message.lastIndexOf("ERROR", 0) === 0 ){
		$("#"+responsediv).atf_alert(message)	
	}else if(message.lastIndexOf("WARN", 0) === 0){
		$("#"+responsediv).atf_warning(message)
	}else if(message.lastIndexOf("SUCCESS", 0) === 0){
		$("#"+responsediv).atf_success(message)
	}else{
		$("#"+responsediv).atf_info(message)
	}
}

uft.showWaitDialog = function(title, message){
//	$("#ajax_loader").show();
	if( typeof title != undefined){
		$('#dialogWait').find(".modal-header").text(title)
	}else{
		$('#dialogWait').find(".modal-header").text("Loading...")
	}
	
	if( typeof message != undefined){
		$('#dialogWait').find(".modal-message").text(message)
	}else{
		$('#dialogWait').find(".modal-message").text("")
	}
	
	$('#dialogWait').modal();
}
uft.hideWaitDailog = function(){
//	$("#ajax_loader").hide();
	$('#dialogWait').modal("hide");
}

uft.testSshConnection= function(hostname,username, password, port, responsediv){
	profileController.testSshConnection(hostname,username,password, port, {
		callback:function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Testing Connection...");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	});
}
uft.testProfileConnection = function(profileId, responsediv){
	taskManager.testConnection(profileId, {
		callback:function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Testing Connection...");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	});
}
uft.updateServerProfile = function(profileId, responsediv){
	taskManager.updateServersList(profileId, {
		callback:function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Updating the Server List. Might take a while");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	});
}

uft.getDeploymentOptions = function(serverId){
	serverController.getDeployOptions(serverId, {
		callback:function(data){
			dwr.util.setValues(data);
			dwr.util.addOptions("deployFiles", data.deployFiles);
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Deployment options");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	});
}

uft.deployApplication= function(options, responsediv){
	taskManager.deployApplication(options,{
			callback:function(data){		
				if(data == "OK"){
				  data="SUCCESS: Scheduled  OK";
				  var taskObj ={taskId: "S"+options.serverId, serverId:options.serverId,  status: "Scheduled",  task: "DEPLOY", serverName:options.servername,comment:"Deploy Scheduled"}
				  serverTaskStatusUpdater.NotifyAll(taskObj);
				}
				uft.generateAlert(data,responsediv);

			}
	 	}); 	
}
uft.getAuditData= function(serverId){
	serverController.getAuditData(serverId, 5, {
		callback: function(data){
			$("#auditPanelTableContainer tbody").empty()
			if( !jQuery.isEmptyObject(data)){
				jQuery.each( data, function( i, val ) {
					var tr= $('<tr>' , {
						html : [ 
						         $('<td>', {
						        	 text: val.task
						         }),
						         $('<td>', {
						        	 text: uft.getDataFormat(val.gentime, "MM/DD/YY hh:mm A")
						         }),
						         $('<td>', {
						        	 text: val.username
						         }),
						         $('<td>', {
						        	 text: val.comments
						         }),
						       ]
					})
					$("#auditPanelTableContainer > tbody:first").append(tr)
				})
			}
		}
	})
}

uft.getDataFormat = function(dt, format){
	if( typeof dt != undefined && dt != "" && dt != null){
		var dayWrapper = moment(dt).format(format);
		return dayWrapper
	}else{
		return "";
	}
	
}
uft.getDateObject = function(st, format){

	if( typeof st != undefined && st != ""){
		var date = moment(st, format).toDate();
		return date
	}else{
		return null;
	}
	
}

uft.emptyDiv = function(id){
	if( $('#'+id).length > 0){
		$('#'+id).empty();
	}
}

uft.addDefaultsPreference = function(responsediv){
	preferenceController.addOrUpdateDefaultsPreference({
		callback: function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Adding Default Preference...");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
}

uft.getAllAuditList= function(maxResults, filterObj){
	var auditList;
	profileController.getAllAuditFiltered(maxResults, filterObj,{
		async: false,
		callback: function(data){
			auditList= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting data...");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	
	
	return auditList;
}

uft.showProfilePopover = function(ele, data){
	if( data != "null"){
		$(ele).popover(
		        {
		          placement: "right",
		          title: "TEST",
		          content:"TEST",
		          trigger: 'focus click'
		        }
		 );
	}else{
		$(ele).popover(
		        {
		          placement: "right",
		          title: "Profile ",
		          content:"Profile Unvailable",
		          trigger: 'focus click'
		        }
		 );
	}
	
}

uft.showServerPopover = function(ele, data){
	if( data != "null"){
		console.log(data)
		//$(ele).popover(
		//        {
	//	          placement: "right",
	//	          title: "TEST",
	//	          content:"TEST",
	//	          trigger: 'focus click'
	//	        }
	//	 );
	}else{
	//	$(ele).popover(
	//	        {
	//	          placement: "right",
	//	          title: "Server",
	//	          content:"Server Unvailable",
	//	          trigger: 'focus click'
	//	        }
	//	 );
	}
}
	
uft.getProfilePreference= function(profileObj, preferenceName){
	var pValue=""
	if( !jQuery.isEmptyObject(profileObj)){
		var prefArray=profileObj.preference
		if( !jQuery.isEmptyObject(prefArray)){
			jQuery.each( prefArray, function( i, val ) {	
				if(val.pName === preferenceName){
					pValue= val.pValue;
				}
			});
		}
	}
	return pValue;
}

uft.startTimer = function(id, callbackFn, interval){
	//console.log(id)
		if( !uft.timers[id] ){
			uft.timers[id]=[setInterval(callbackFn,interval),callbackFn];
		}else{
			uft.changeTimer(id, callbackFn, interval)
		}
}

uft.stopTimer = function(id){
	if( !uft.timers[id] )return;
	clearInterval(uft.timers[id][0])
	delete uft.timers[id];
}
uft.changeTimer = function(id, callbackFn, interval){
	if( !uft.timers[id] )return;
	 clearInterval(uft.timers[id][0]);
	 setInterval(uft.timers[id][1],interval);
}
uft.getDefaultHttpMaxRequest = function (){
	var maxhttpValue="";
	preferenceController.getPreferenceByNameScope("HTTP_REQUEST_MAX", "GLOBAL",{
		async: false,
		callback: function(data){
			maxhttpValue= data;
		}
	})
	return maxhttpValue;
}

uft.encrptyPassword = function (value){
	var enValue="";
	preferenceController.encryptPassword(value,{
		async: false,
		callback: function(data){
			enValue= data;
		}
	})
	return enValue;
}

uft.decryptPassword = function (value){
	var enValue="";
	preferenceController.decryptPassword(value,{
		async: false,
		callback: function(data){
			enValue= data;
		}
	})
	return enValue;
}


uft.getWasConfigurationServerList= function(id){
	var serverList;
	profileController.getWasConfigurationServerList(id,{
		async: false,
		callback: function(data){
			serverList= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Config List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return serverList;
}

uft.getWasConfigFile = function (profileId, sName){
	var configProp= ""
	profileController.getWasConfig(profileId,sName,{
		async: false,
		callback: function(data){
			configProp= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Config List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return configProp;
}

uft.getWasConfigFilePath = function (profileId, sName){
	var configPropPath= ""
		profileController.getWasConfigFilePath(profileId,sName,{
			async: false,
			callback: function(data){
				configPropPath= data;
			},
			preHook:function(){
				uft.showWaitDialog("Please Wait..", "Getting Config List");
			},
			postHook:function(){
				uft.hideWaitDailog();
			}
		})
		return configPropPath;
}
uft.addServerConfigToProfile = function(id, sName, responsediv){
	profileController.addWasServerConfigToProfile(id,sName,{
		callback: function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			$("#"+responsediv).atf_display_loader("Adding...", "Add Server")
		}
		
	})
}

uft.removeServerConfigFileProfile = function(id, sName, responsdiv){
	profileController.removeWasServerConfigFileProfile(id,sName,{
		callback: function(data){
			uft.generateAlert(data, responsediv)
		},
		preHook:function(){
			$("#"+responsediv).atf_display_loader("Adding...", "Deleting Server")
		}
		
	})
}
uft.uploadWasConfigFile= function(profileId, sName, configFile, responsediv){
		profileController.uploadWasConfigFile(profileId,sName,configFile,{
			async: false,
			callback: function(data){
				uft.generateAlert(data, responsediv)
			},
			preHook:function(){
				uft.showWaitDialog("Please Wait..", "Uploading Config File");
			},
			postHook:function(){
				uft.hideWaitDailog();
			}
		})
}

uft.getUsersData = function (){
	var userList;
	profileController.getUsersData({
		async: false,
		callback: function(data){
			userList= data;
		}
	})
	return userList;
}

uft.deleteUsersData = function (userid,responseDiv){
	if(userid != ""){
		profileController.deleteUsersData(userid,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Delete "+data)
			}
		});
	}
}
uft.saveOrUpdateUserDetail = function(userObj, responseDiv){
	if(userObj.userId == ""){
		profileController.addNewUser(userObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Add "+data)
				
			}
		});
	}else{
		profileController.updateUser(userObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Update "+data)
				
			}
		});
	}
}

uft.saveOrUpdateLdapConfig = function(ldapObj, responseDiv){
	if(ldapObj.ldapId == ""){
		profileController.addNewLdapConfig(ldapObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Add "+data)
				
			}
		});
	}else{
		profileController.updateLdapConfig(ldapObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Update "+data)
				
			}
		});
	}
}
uft.getLdapConfig = function (){
	var ldapConfigObj;
	profileController.getLdapConfig({
		async: false,
		callback: function(data){
			ldapConfigObj= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Users List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return ldapConfigObj;
}

uft.udateDivStatus = function(id, status){
	$("#"+id).empty()
	if( status == "SUCCESS"){
		$("#"+id).html("<i class='fa fa-circle text-success'></i>")
	}
	if ( status == "ERROR"){
		$("#"+id).html("<i class='fa fa-circle text-danger'></i>")
	}
}

uft.getDpServiceUniqueRegions= function(){
	var dpServiceRegions;
	dpController.getDpServiceUniqueRegions({
		async: false,
		callback: function(data){
			dpServiceRegions= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Regions List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return dpServiceRegions;
}

uft.saveOrUpdateDpService= function(serviceObj, responseDiv){
	if(serviceObj.id == ""){
		dpController.addDpService(serviceObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Add "+data)
				
			}
		});
	}else{
		dpController.updateDpService(serviceObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Update "+data)
				
			}
		});
	}
}
uft.getDpGetAllServiceByRegion= function(regionName){
	var allServices;
	dpController.getDpGetAllServiceByRegion(regionName,{
		async: false,
		callback: function(data){
			allServices= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Services List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return allServices;
}

uft.getEmptyDpService= function(){
	var dpService;
	dpController.getEmptyDpService({
		async: false,
		callback: function(data){
			dpService= data;
		}	
	})
	return dpService;
}
uft.getEmptySchedulerJob= function(){
	var job;
	schedulerController.getEmptySchedulerJob({
		async: false,
		callback: function(data){
			job= data;
		}	
	})
	return job;
}
uft.getSchedulerUniqueRegions= function(){
	var schedulereRegions;
	schedulerController.getSchedulersUniqueRegions({
		async: false,
		callback: function(data){
			schedulereRegions= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Regions List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return schedulereRegions;
}

uft.getSchedulerJob= function(jobId){
	var jobObj;
	schedulerController.getSchedulerJob(jobId,{
		async: false,
		callback: function(data){
			jobObj= data;
		}	
	})
	return jobObj;
	
}


uft.getSchedulersByRegion = function(regionName){
	var schedulers;
	schedulerController.getSchedulersByRegion(regionName,{
		async: false,
		callback: function(data){
			schedulers= data;
		},
		preHook:function(){
			uft.showWaitDialog("Please Wait..", "Getting Schedulers List");
		},
		postHook:function(){
			uft.hideWaitDailog();
		}
	})
	return schedulers;
}
uft.saveOrUpdateSchedulerJob= function(serviceObj, responseDiv){
	if(serviceObj.jobId == ""){
		schedulerController.addSchedulerJob(serviceObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Add "+data)
				
			}
		});
	}else{
		schedulerController.updateSchedulerJob(serviceObj,{
			async: false,
			callback:function(data){
				$("#"+responseDiv).atf_success("Update "+data)
			}
		});
	}
}

uft.deleteSchedulerJob= function(jobid,responseDiv){
	schedulerController.deleteSchedulerJob(jobid,{
		async: false,
		callback:function(data){
			$("#"+responseDiv).atf_success("Add "+data)
			
		}
	});
}

uft.schedulerJob=function(jobid,responseDiv){
	schedulerManager.addToScheduler(jobid,{
		async: false,
		callback:function(data){		
			uft.generateAlert(data, responseDiv)
			
		}
	});
}
uft.unSchedulerJob=function(jobid,responseDiv){
	schedulerManager.removeSchedulerJob(jobid,{
		async: false,
		callback:function(data){		
			uft.generateAlert(data, responseDiv)
			
		}
	});
}
uft.updateSchedulerBadge= function(){
	if ( $( "#scheduleTaskCount" ).length ) {
		$("#scheduleTaskCount").text(uft.getSchedulerJobsList().length);
		
	}
}

uft.getSchedulerJobsList=function(){
	var jobsList;
	schedulerManager.getSchedulerList({
		async: false,
		callback:function(data){		
			jobsList=data;
		}
	})
	return jobsList;
}

uft.getJobSummaryDetails= function(jobId, jobname, jobRegion, cDate){
	var jobSummaryList;
	schedulerController.getJobSummaryDetails(jobId, jobname, jobRegion, cDate,{
			async: false,
			callback:function(data){
				jobSummaryList=data
			}
		})
	return jobSummaryList;
}
//timer = {
//	    timers:{},
//	    inc:0,
//	    start:function(cb,gap) {
//	        var key = timer.inc;
//	        timer.inc++;
//	        timer.timers[key] = [setInterval(cb,gap),cb];
//	        return key;
//	    },
//	    stop:function(id) {
//	        if( !timer.timers[id]) return;
//	        clearInterval(timer.timers[id][0]);
//	        delete timer.timers[id];
//	    },
//	    change:function(id,newgap) {
//	        if( !timer.timers[id]) return;
//	        clearInterval(timer.timers[id][0]);
//	        setInterval(timer.timers[id][1],newgap);
//	    }
//	};